package connection;

import form.RequestConnectionDialog;
import form.HostDialog;
import form.MainFrame;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import p2pExceptions.BufferNotReadyException;

/**
 *
 * @author christ66
 */
public class HostManager extends Thread {

    public HostManager() {
        this(5678);
        connected = false;
    }

    public HostManager(int port) {
        this.port = port;
        connected = false;
    }

    public void startHost() throws IOException {
        try {
            server = new ServerSocket(port);
            Logger.getLogger(HostManager.class.getName()).log(Level.INFO, "Waiting for connection..");
            socket = server.accept();
            Logger.getLogger(HostManager.class.getName()).log(Level.INFO, "Connection accepted..");
            writer = new PrintWriter(socket.getOutputStream(), true);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 
            String handshake = reader.readLine();

            requestDialog = new RequestConnectionDialog(parentDialog, true);

            oppPlayerName = handshake.substring(handshake.indexOf("nickName=") + "nickName=".length(), handshake.indexOf(";", handshake.indexOf("nickName") + 1));
            System.out.println("OPPPPPPP: "+oppPlayerName);
            MainFrame.oppPlayer = oppPlayerName;
            color = handshake.substring(handshake.indexOf(";")+1,handshake.indexOf("]") );
            requestDialog.setNameText(oppPlayerName);
            requestDialog.setLocationRelativeTo(parentDialog);
            requestDialog.setVisible(true);

            System.out.println("Handshake = " + handshake);
            //System.out.println("Color = " + color);
            

            if (hostDiag != null && requestDialog.getReturnStatus() == 1) { //If host accepts connection
                hostDiag.dispose();
                connected= true;
                loadConfig();
                //writer.println("Play");
            }
            else if (hostDiag != null && requestDialog.getReturnStatus() == 0) {
                hostDiag.dispose();
                requestDialog.dispose();
                connected = false;
                writer.println("Decline");
            }

        } catch (SocketException ex) {//Lets punt this exception to the thread.
            throw ex;
        } catch (IOException ex) {
            Logger.getLogger(HostManager.class.getName()).log(Level.SEVERE, "Teh fuk?", ex);
            throw ex;
        }

    }
    private void loadConfig(){    //This would check the saved file with opp player. If exist then send hash to other player.
        File file = new File(MainFrame.currentPlayer.getNickName()+oppPlayerName+".chs");
        if(file.exists()){
            try{
            fstream = new FileInputStream(file);
            scanner = new Scanner(fstream);
                while (scanner.hasNextLine()) {                   
//                    if(hash.equals(black)){hostColor = Color.BLACK;}
//                    if(hash.equals(white)){hostColor = Color.WHITE;}
                    hash = scanner.nextLine();
                     }            
            fstream.close();
            scanner.close();
            System.out.println("Host Seding filename:"+MainFrame.currentPlayer.getNickName()+oppPlayerName+"  and Hash: "+hash);
            writer.println("[file="+oppPlayerName+";hash="+hash+"]");
            String isMatch = reader.readLine();
            if(isMatch.equals("LoadGame")){
                isLoad = true;
                MainFrame.board.convertHash(hash);
            }
            System.out.println(isMatch);
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(!file.exists()){
            hash = null;
            isLoad = false;
            writer.println("Play");           
        }
       
    }

    public void stopHost() throws IOException {
        try {
            if (server != null) {
                server.close();
            }
            if (socket != null) {
                socket.close();
            }
            if (writer != null) {
                writer.close();
            }
            if (reader != null) {
                reader.close();
            }
            connected = false;
        } catch (IOException ex) {
            Logger.getLogger(HostManager.class.getName()).log(Level.SEVERE, "I only wanted to close things...", ex);
            throw ex;
        }
    }
    
    //not used???
    public boolean confirmMove() throws IOException, BufferNotReadyException{
        movesConfirmed=false;
        System.out.println("confirmMove();");//troubleshooter
        try {
            if(reader.ready()){
            	readBuffer=reader.readLine();
        		System.out.println("readbuffer = " + readBuffer);//troubleshooter

	                 if (readBuffer.charAt(0) == '1') {
                		System.out.println("Client received move "+ readBuffer.substring(2,6));//troubleshooter
                    	movesConfirmed = true;
                    	//return true;
	                 } else{
	                	System.out.println("que?");
	                    System.out.println(readBuffer);
	                    //return false;
	                 }
            }//end reader ready
            else System.out.println("reader dead");//troubleshooter

        } catch (IOException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        }
		return false;
    }
    

    public String receiveData() throws IOException, BufferNotReadyException{
        try {
            if(reader.ready()){
            	readBuffer=reader.readLine();
    			if (!(oldBuffer.equals(readBuffer))){ //something new
                	oldBuffer=readBuffer;
                	return readBuffer;
    			}//end new data    
            }//end reader ready
        } catch (IOException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        }
		return null;
    }

    public boolean isLoad(){
        return isLoad;
    }

    public String getHash(){
        return hash;
    }

    public String getAddress() {
        return server.getInetAddress().toString();
    }
    
    public String getOpponentColor() {
        return color;
    }
    
    
    public void sendData(String data) {
    	//movesConfirmed=false;
        writer.println(data);
        System.out.println("Host sending..." + data);
    }

    public ServerSocket getServer() {
        return server;
    }

    public Socket getSocket() {
        return socket;
    }

    public PrintWriter getWriter() {
        return writer;
    }

    public BufferedReader getReader() {
        return reader;
    }

    @Override
    public void run() {
        try {
            startHost();
        }catch (SocketException ex){
            Logger.getLogger(HostManager.class.getName()).log(Level.INFO, "We probably stopped listening for connections..", ex);
        }
        catch (Exception ex) {
            Logger.getLogger(HostManager.class.getName()).log(Level.SEVERE, "I'm not sure what the f!#$ happened.. read the stack trace..", ex);
        }
		while (connected){
			try {
				if (connected && reader.ready()){
					_fireStreamEvent();
				}
			} catch (IOException e) {}
		}
    }

    public void setParentDialog(javax.swing.JFrame parent) {
        this.parentDialog = parent;
    }

    public void setPort(int port) {
        if (port >= 1 && port <= 65536)
            this.port = port;
    }

    public int getPort() {
        return port;
    }

    public boolean isConnected() {
        return connected;
    }

    public void setDialog(HostDialog dia){
        hostDiag = dia;
    }

    public Color getHostColor(){
            return hostColor;
    }
    
    public boolean getMovesConfirmed() {
        return movesConfirmed;
    }
    
    public boolean getHostConnect() {
        return connected;
    }
    
    public static void wait (int n){
        long t0, t1;
        t0 =  System.currentTimeMillis();
        do{
            t1 = System.currentTimeMillis();
        }
        while ((t1 - t0) < n);
    }

    private Socket socket;
    private PrintWriter writer;
    private BufferedReader reader;
    private String readBuffer;
    private String oldBuffer = "";
    private ServerSocket server;
    private HostDialog hostDiag = null;
    private boolean connected = false;
    private int port;
    private boolean movesConfirmed = false;
    private javax.swing.JFrame parentDialog;
    private RequestConnectionDialog requestDialog;
    private String color;
    private String oppPlayerName, hash = null;
    private FileInputStream fstream = null;
    private Scanner scanner = null;
    private boolean isLoad = false;
    private Color hostColor; //if saved game found
    private String black = "BLACK"+'\n';
    private String white = "WHITE"+'\n';

    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^listener stuff^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    @SuppressWarnings("rawtypes")
	private ArrayList _listeners = new ArrayList();

    @SuppressWarnings("unchecked")
	public synchronized void addStreamListener(StreamListener l) {
        _listeners.add(l);
    }
    
    public synchronized void removeStreamListener(StreamListener l) {
        _listeners.remove(l);
    }
     
    @SuppressWarnings("rawtypes")
	private synchronized void _fireStreamEvent() {
        StreamEvent stream = new StreamEvent(this);
        Iterator listeners = _listeners.iterator();
        while(listeners.hasNext()) {
            ((StreamListener) listeners.next()).streamReceived(stream);
        }
    }
    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^listener stuff^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    


}
